import { cloneElement } from 'react'
import { IComponentMapsType, ComponentMaps } from "./renders";
import { ICmptRenderSchema, RenderSchemaToCmptOpts } from './types';
import { IFormItem } from '@/components/IForm';


/** 查找可用组件 */
export function findCmptByType(type: IComponentMapsType, opts?: any) {
  if (!ComponentMaps[type]) {
    return <div>未找到组件!</div>;
  }
  return ComponentMaps[type]
}

/** 将schema渲染为组件 */
export function renderSchemaToCmpt(schema: ICmptRenderSchema, opts: RenderSchemaToCmptOpts) {
  const { type, evt, value, data } = schema;
  const Cmpt = findCmptByType(type) as any;
  const doAction = opts.onAction;
  let props: Record<string, any> = {
    size: 'xs', 
    defaultValue: value,
    onChange: (e: any) => doAction({event: evt, data: e})
  };
  
  if (type == 'input') {
    props.onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      doAction({
        event: evt,
        data: e.target.value
      })
    };
  }

  if (type == 'switch') {
    props.size = 'sm';
    props.onChange = (e: any) => doAction({ event: evt, data: e.target.checked })
  }

  if (type == 'select') {
    props.data = data;
  }

  if (Cmpt.render) {
    return cloneElement(Cmpt.render(props), props);
  }

  return cloneElement(<Cmpt />, props)
}


export function renderSchemaPane(schema: ICmptRenderSchema, index: number, opts: RenderSchemaToCmptOpts) {
  const { label } = schema;
    return (
      <IFormItem key={index} label={label} >
        { renderSchemaToCmpt(schema, opts) }
      </IFormItem>
    )
}